package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.DualAuthorizationParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class CommonReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String content = jsonObjectParamContent.getString("dataContent");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(content);
        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("mobileMd5")) || StrUtil.isEmpty(jsonObject.getString("idCard")) || StrUtil.isEmpty(jsonObject.getString("sex")) || StrUtil.isEmpty(jsonObject.getString("cityCode")) || StrUtil.isEmpty(jsonObject.getString("loanAmount")) || StrUtil.isEmpty(jsonObject.getString("loanTime")) || StrUtil.isEmpty(jsonObject.getString("house")) || StrUtil.isEmpty(jsonObject.getString("car")) || StrUtil.isEmpty(jsonObject.getString("gjj")) || StrUtil.isEmpty(jsonObject.getString("shebao")) || StrUtil.isEmpty(jsonObject.getString("baoxian")) || StrUtil.isEmpty(jsonObject.getString("zhima")) || StrUtil.isEmpty(jsonObject.getString("huabei")) || StrUtil.isEmpty(jsonObject.getString("baitiao")) || StrUtil.isEmpty(jsonObject.getString("weili")) || StrUtil.isEmpty(jsonObject.getString("shouru")) || StrUtil.isEmpty(jsonObject.getString("xueli")) || StrUtil.isEmpty(jsonObject.getString("yongtu")) || StrUtil.isEmpty(jsonObject.getString("yuqi")) || StrUtil.isEmpty(jsonObject.getString("xinyongka")) || StrUtil.isEmpty(jsonObject.getString("gongzuo")) || jsonObject.getInteger("age") == null){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);


        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String content = jsonObjectParamContent.getString("dataContent");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(content);

        DualAuthorizationParam dualAuthorizationParam = JSON.parseObject(paramContentData, DualAuthorizationParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(dualAuthorizationParam.getMobile());
        userDataParam.setRealName(dualAuthorizationParam.getRealName());

        String outOrderNo = dualAuthorizationParam.getProductId();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), outOrderNo);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {

        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("status", "000");
        returnObject.put("message", "撞库成功！");
        JSONObject dataObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        // 推送原价(分润渠道返回，固价渠道不返回)
        BigDecimal priceAmount = BigDecimal.ZERO;
        if (ObjectUtil.equals(ProfitSharingEnum.PROFITPRICE.getValue(),sourceBaseInfo.getPriceType())){
            priceAmount = pushResultInfo.getPriceAmount();//分润前价格
        }
        dataObject.put("price", priceAmount);

        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue()) ){

            // 下游是 非 apis 类型
            dataObject.put("companyName", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", companyLogo);
            }

            dataObject.put("productName", thirdBaseInfo.getProductName());
            dataObject.put("productId", pushResultInfo.getOutOrderNo());

            //协议地址
            for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("protocolName",protocolInfo.getProtocolName());
                jsonObject.put("protocolUrl", protocolInfo.getProtocolUrl());
                jsonArray.add(jsonObject);
            }
        }else{
            // 下游是 非 apis 类型
            dataObject.put("companyName", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
            }

            dataObject.put("productName", merchantBaseInfo.getInfoName());
            dataObject.put("productId", pushResultInfo.getOutOrderNo());


            //协议地址

            JSONObject jsonObject = new JSONObject();
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            jsonObject.put("protocolName","授权协议");
            jsonObject.put("protocolUrl", protocolUrl);
            jsonArray.add(jsonObject);
        }




        dataObject.put("protocolList", jsonArray);
        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("status", "500");
        returnObject.put("message", message);
        returnObject.put("data", new JSONObject());
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("status", "000");
        returnObject.put("message", "推送成功");
        returnObject.put("data", new JSONObject());
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        DualAuthorizationParam dualAuthorizationParam = JSON.parseObject(paramContent, DualAuthorizationParam.class);

        UserDataParam userDataParam = new UserDataParam();

        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
        userDataParam.setOutOrderNo(String.valueOf(randomInt));

        userDataParam.setMobileMd5(dualAuthorizationParam.getMobileMd5());

        userDataParam.setMobile(dualAuthorizationParam.getMobile());

        userDataParam.setRealName(dualAuthorizationParam.getRealName());

        if (StringUtils.isNotEmpty(dualAuthorizationParam.getIdCar())){
            userDataParam.setIdCard(dualAuthorizationParam.getIdCar());
        }

        userDataParam.setSex(dualAuthorizationParam.getSex());

        userDataParam.setAge(dualAuthorizationParam.getAge());

        userDataParam.setCityCode(dualAuthorizationParam.getCityCode());

        userDataParam.setXinyongka(dualAuthorizationParam.getXinyongka());

        userDataParam.setYongtu(dualAuthorizationParam.getYongtu());

        userDataParam.setXueli(dualAuthorizationParam.getXueli());

        userDataParam.setShouru(dualAuthorizationParam.getShouru());

        userDataParam.setWeili(dualAuthorizationParam.getWeili());

        userDataParam.setBaitiao(dualAuthorizationParam.getBaitiao());

        userDataParam.setHuabei(dualAuthorizationParam.getHuabei());

        if (StringUtils.isNotEmpty(dualAuthorizationParam.getUserIp())){
            userDataParam.setUserIp(dualAuthorizationParam.getUserIp());
        }else {
            userDataParam.setUserIp("127.0.0.1");
        }

        userDataParam.setLoanAmount(dualAuthorizationParam.getLoanAmount());

        userDataParam.setHouse(dualAuthorizationParam.getHouse());

        userDataParam.setBaoxian(dualAuthorizationParam.getBaoxian());


        userDataParam.setYuqi(dualAuthorizationParam.getYuqi());


        userDataParam.setGjj(dualAuthorizationParam.getGjj());


        userDataParam.setZhima(dualAuthorizationParam.getZhima());


        userDataParam.setShebao(dualAuthorizationParam.getShebao());


        userDataParam.setCar(dualAuthorizationParam.getCar());


        userDataParam.setGongzuo(dualAuthorizationParam.getGongzuo());


        userDataParam.setLoanTime(dualAuthorizationParam.getLoanTime());


        return userDataParam;
    }

}
